package org.dromara.tearoom.dubbo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.esotericsoftware.minlog.Log;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.tearoom.api.RemoteOrderService;
import org.dromara.tearoom.domain.TerOrder;
import org.dromara.tearoom.domain.bo.TerHornEquipmentBo;
import org.dromara.tearoom.domain.bo.TerRoomDetailsBo;
import org.dromara.tearoom.domain.enums.IotDeviceClassEnum;
import org.dromara.tearoom.domain.enums.OrderStatusContent;
import org.dromara.tearoom.domain.enums.RoomStatusEnum;
import org.dromara.tearoom.domain.vo.TerHornEquipmentVo;
import org.dromara.tearoom.domain.vo.TerOrderVo;
import org.dromara.tearoom.mapper.TerOrderMapper;
import org.dromara.tearoom.service.ITerHornEquipmentService;
import org.dromara.tearoom.service.ITerIotDeviceService;
import org.dromara.tearoom.service.ITerRoomDetailsService;
import org.dromara.tearoom.service.IWxMaNoticeService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
@DubboService
@Slf4j
public class RemoteOrderServiceImpl implements RemoteOrderService {
    private final TerOrderMapper baseMapper;
    private final ITerIotDeviceService terIotDeviceService;
    private final ITerRoomDetailsService terRoomDetailsService;
    private final IWxMaNoticeService wxMaNoticeService;
    private final ITerHornEquipmentService terHornEquipmentService;
    /**
     * 批量更新逻辑
     * */
    @Override
    public  void updateOrderBatch(LocalDateTime date) {
        List<String> idList = new ArrayList<>();
        TerRoomDetailsBo tbo = new TerRoomDetailsBo();
        tbo.setUpdateBy(1L);
        tbo.setStatus(RoomStatusEnum.NEED_CLEAN.getType());
        List<TerOrderVo> orderVoList = queryPageByDate(date);
        if(CollUtil.isNotEmpty(orderVoList)){
            for(TerOrderVo vo: orderVoList){
                if(StrUtil.isBlank(vo.getIsRenew())){
                    log.info("开始断电打扫");
                    tbo.setId(vo.getTearoomId());
                    terRoomDetailsService.updateByBo(tbo);
                    terIotDeviceService.operateDeviceOnOffByClass(vo.getTearoomId(),false, IotDeviceClassEnum.CHOPPER.getType());
                    wxMaNoticeService.needClean(vo.getId());
                    ThreadUtil.execAsync(()->wxMaNoticeService.cleanOrder(vo.getId()));
                    idList.add(vo.getId());
                }
            }
        }
        if (!idList.isEmpty()) {
            log.info("按时间修改订单");
            updateOrderByList(idList);
            idList.clear();
        }
    }

    @Override
    public  void broadcastTask(LocalDateTime date) {
        TerHornEquipmentBo thbo =null;
        List<TerHornEquipmentVo> thlist =terHornEquipmentService.selectEquipmentAndCookie();

        List<TerOrderVo> ordersLastList =queyPageByEnddate(date,thlist.get(0).getLastSecn());
        if(ordersLastList!=null&&ordersLastList.size()>0){
            for(TerHornEquipmentVo thvo:thlist){
                for(TerOrderVo vo: ordersLastList){
                    if(thvo.getTeroomId().equals(vo.getTearoomId())){
                        thbo = BeanUtil.toBean(thvo, TerHornEquipmentBo.class);
                        terHornEquipmentService.idlyBroadcast(thbo,"auto");
                    }
                }
            }
        }

        List<TerOrderVo> ordersFirstList =queyPageByEnddate(date,thlist.get(0).getFirstSecn());
        if(ordersFirstList==null||ordersFirstList.size()<=0)return;

        for(TerHornEquipmentVo thvo:thlist){
            for(TerOrderVo vo: ordersFirstList){
                if(thvo.getTeroomId().equals(vo.getTearoomId())){
                    thbo = BeanUtil.toBean(thvo, TerHornEquipmentBo.class);
                    terHornEquipmentService.idlyBroadcast(thbo,null);
                }
            }
        }

    }

    @Override
    public void delOrderBatch(LocalDateTime date) {
        delByTime(date);
        updateExpiredOrder(date);
    }
    public void updateExpiredOrder(LocalDateTime date){
        LambdaUpdateWrapper<TerOrder> luw = new LambdaUpdateWrapper<>();
        luw.eq(TerOrder::getOrderStatus, OrderStatusContent.CONFIRMED)
                .le(TerOrder::getEndTime, date)
                .set(TerOrder::getOrderStatus, OrderStatusContent.EXPIRED);
        baseMapper.update(null, luw);
    }


    /**
     * 按时间修改订单
     * @param list
     */

    public int updateOrderByList(List<String> list) {
        if (CollectionUtil.isEmpty(list)) {
            return 0; // 或抛出业务异常
        }
        LambdaUpdateWrapper<TerOrder> luw = new LambdaUpdateWrapper<>();
        luw.in(TerOrder::getId, list)
                .set(TerOrder::getOrderStatus, OrderStatusContent.COMPLETED)
                .set(TerOrder::getUpdateTime, LocalDateTime.now());

        return baseMapper.update(null, luw);
    }

    /**
     * 按时间查询订单
     * @param date
     */
    public List<TerOrderVo> queryPageByDate(LocalDateTime date){
        // 获取当天0点时间
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 1. 检查时间参数合法性（假设 date 是方法入参）
        if (date == null) {
            throw new IllegalArgumentException("时间参数不能为空");
        }
        // 2. 构建查询条件
        LambdaQueryWrapper<TerOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(TerOrder::getOrderStatus, OrderStatusContent.CHECKED_IN)
            .ge(TerOrder::getEndTime, todayStart)  // 大于等于当天0点
            .le(TerOrder::getEndTime, now)
            .orderByAsc(TerOrder::getEndTime);
        // 3. 执行查询
        List<TerOrderVo> result = baseMapper.selectVoList(lqw);
        return result;
    }

    public List<TerOrderVo> queyPageByEnddate(LocalDateTime date,Integer minNum){
        if (date == null) {
            throw new IllegalArgumentException("时间参数不能为空");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        return queryCandidateOrders(minNum ,date.format(formatter));
    }

    public int delByTime(LocalDateTime date){
        LambdaQueryWrapper<TerOrder> lqw = Wrappers.lambdaQuery();
        lqw.le(TerOrder::getCreateTime,date.minusHours(1));
        lqw.eq(TerOrder::getOrderStatus,OrderStatusContent.UN_PAY);
        return baseMapper.delete(lqw);
    }


    private List<TerOrderVo> queryCandidateOrders(
                                             int minutesOffset, String baseTime) {
        LambdaQueryWrapper<TerOrder> qw = Wrappers.lambdaQuery();

        qw.eq(TerOrder::getOrderStatus,OrderStatusContent.CHECKED_IN).isNull(TerOrder::getIsRenew)
                .apply("DATE_FORMAT(DATE_SUB(end_time, INTERVAL {0} MINUTE), '%Y-%m-%d %H:%i') = {1}",minutesOffset, baseTime)
                .orderByAsc(TerOrder::getOpenId).orderByAsc(TerOrder::getStartTime);
        return baseMapper.selectVoList(qw);
    }


}
